

$(document).ready(function(){
    // render
    loadData();
    // event
    bindEvent();
});

function loadProductDetailCode(){
    var now = new Date();
    ProductDetail_code_auto = "CTSP" + now.getTime();
    ISS.DOM.setVal('#ProductDetail_code', ProductDetail_code_auto);
}

function loadProductCommonCode(){
    var now = new Date();
    ProductCommon_code_auto = "SP" + now.getTime();
    ISS.DOM.setVal('#ProductCommon_code', ProductCommon_code_auto);
}

function loadData() {
    loadProductCommonCode();
    loadProductDetailCode();

    //Lay het danh sach san pham
/*    ISS.BACKEND.request({
        url: '../../service/admin/ad_GetAllProduct',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapAllProductToView(responseContent);
        }
    });*/

    ISS.BACKEND.request({
        url: '../../service/admin/getAllProductListInProduct',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapAllProductCategoryToViewInProduct(responseContent);
        }
    });

    ISS.BACKEND.request({
        url: '../../service/admin/ad_GetAllColor',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapAllColorToView(responseContent);
        }
    });

    ISS.BACKEND.request({
        url: '../../service/admin/ad_GetAllSize',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapAllSizeToView(responseContent);
        }
    });

    ISS.BACKEND.request({
        url: '../../service/admin/ad_GetAllMotifInProductDetail',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapAllMotifToView(responseContent);
        }
    });
}

function bindEvent() {
    ISS.EVENT.bindEvent('#ProductCommon_Add1', 'click', function () {
        if(validate()){
            sendInfo();
        }
        else {
            var htmlText = '<div class="box s-error mbs msgBox l-pageWrapper mbm">\
                                <div class="pam">Cập nhất sản phẩm thất bại</div>\
                            </div>';
            ISS.DOM.before('.l-register__benefits', htmlText);
        }
    });

    ISS.EVENT.bindEvent('#buttonAddProductDetail_Cancel', 'click', function () {
        hideBoxConfirm();
        /*var _url = '../../ad-product-common.jsp';
        ISS.WINDOW.location(_url);*/
    });

    ISS.EVENT.bindEvent('#buttonAddProductDetail_Agree', 'click', function () {
        hideBoxConfirm();
        ISS.DOM.removeClass('#boxDetailProduct', 'hideBox');
        /*ISS.DOM.removeClass('#boxDetailProduct', 'hideBox');
        ISS.DOM.addClass('#buttonProductCommon', 'hideBox');*/
    });

    ISS.EVENT.bindEvent('#buttonAddProductDetailPicture_Agree', 'click', function () {
        ISS.DOM.addClass('#boxTrackConfirmPicture', 'hideBox');
        ISS.DOM.addClass('#buttonProductDetail', 'hideBox');
        ISS.DOM.removeClass('#boxDetailProductPicture', 'hideBox');
    });

    ISS.EVENT.bindEvent('#ProductDetail_Add1', 'click', function () {
        if(validate()){
            sendDetailInfo();
        }
        else {
            var htmlText = '<div class="box s-error mbs msgBox l-pageWrapper mbm">\
                                <div class="pam">Thêm chi tiết sản phẩm thất bại</div>\
                            </div>';
            ISS.DOM.before('.l-register__benefits', htmlText);
        }
    });

    ISS.EVENT.bindEvent('#ProductCommon_Detail', 'click', function () {
        ISS.DOM.removeClass('#boxDetailProduct', 'hideBox');
    });

    ISS.EVENT.bindEvent('#ProductCommon_Quit', 'click', function () {
        ISS.DOM.removeClass('#boxTrackQuitSessionConfirm', 'hideBox');
        /*var _url = '../../ad-product-common.jsp';
        ISS.WINDOW.location(_url);*/
    });

    ISS.EVENT.bindEvent('#buttonQuitSession_Agree', 'click', function () {
        ISS.DOM.removeClass('#boxTrackQuitSessionConfirm', 'hideBox');
        var _url = ISS.SESSION.getSession('contextPath') + '/ad-product-common.jsp';
         ISS.WINDOW.location(_url);
    });

    ISS.EVENT.bindEvent('#buttonQuitSession_Cancel', 'click', function () {
        ISS.DOM.addClass('#boxTrackQuitSessionConfirm', 'hideBox');
    });

    ISS.EVENT.bindEvent('#ProductCommon_Detail_Retype', 'click', function () {
        loadProductCommonCode();
        ISS.DOM.setVal('#ProductCommon_name', "");
        ISS.DOM.setVal('#ProductCommon_information', "");
        ISS.DOM.setVal('#ProductCommon_listProduct', "default_value");
        ISS.DOM.setVal('#ProductCommon_sexual', "non_value");
    });

    ISS.EVENT.bindEvent('#ProductDetail_Cancel1', 'click', function () {
        ISS.DOM.addClass('#boxDetailProduct', 'hideBox');
        ISS.DOM.removeClass('#buttonProductCommon', 'hideBox');
        ISS.DOM.removeClass('#buttonProductCommon_Quit', 'hideBox');
        ISS.DOM.removeClass('#buttonProductCommon_Detail', 'hideBox');
    });

    ISS.EVENT.bindEvent('#ProductDetail_Retype', 'click', function () {
        loadProductDetailCode();
        ISS.DOM.setVal('#ProductDetail_unitPrice', "");
        ISS.DOM.setVal('#ProductDetail_quantity', "");
        ISS.DOM.setVal('#ProductDetail_size', "default_value");
        ISS.DOM.setVal('#ProductDetail_color', "default_value");
        ISS.DOM.setVal('#ProductDetail_motif', "default_value");
    });

    ISS.EVENT.bindEvent('#buttonAddProductDetailPicture_Cancel', 'click', function () {
//        loadDataDetailComplete(code);
        ISS.DOM.addClass('#boxTrackConfirmPicture', 'hideBox');
    });

    ISS.EVENT.bindEvent('#ProductDetail_Picture', 'click', function () {
        ISS.DOM.removeClass('#boxDetailProductPicture', 'hideBox');
        ISS.DOM.addClass('#buttonProductDetail', 'hideBox');
    });

    ISS.EVENT.bindEvent('#ProductDetail_Cancel1', 'click', function () {
        ISS.DOM.addClass('#boxDetailProduct', 'hideBox');
    });

    ISS.EVENT.bindEvent('#ProductCommon_Modified', 'click', function () {
        toEditPage();
    });

    ISS.EVENT.bindEvent('#ProductCommon_Detail_Search', 'click', function () {
        toDetailPage();
    });

    ISS.DOM.html('#upload_template', '<div id="multipleupload">Upload</div>');
    var maCTSP = ISS.DOM.getVal('#ProductDetail_code');
    var _upload = $("#multipleupload").uploadFile({
        url: "../../service/admin/insertProductPicture",
        autoSubmit:false,
        multiple:true,
        fileName:"myfile",
        formData: {"maCTSP": maCTSP}
    });

    ISS.EVENT.bindEvent('#startUpload', 'click', function () {
        _upload.startUpload();
    });

    ISS.EVENT.bindEvent('#ProductDetailPicture_Cancel1', 'click', function () {
        ISS.DOM.addClass('#boxDetailProductPicture', 'hideBox');
    });

    ISS.EVENT.bindEvent('#buttonEditProductDetail_Cancel', 'click', function () {
        ISS.DOM.addClass('#boxTrackConfirm', 'hideBox');
    });

    ISS.EVENT.bindEvent('#buttonSuccessAddProduct_Hide', 'click', function () {
        ISS.DOM.addClass('#boxTrackSuccessAddProductConfirm', 'hideBox');
    });

    ISS.EVENT.bindEvent('#ProductCommon_Search', 'click', function () {
        var maDMSP = ISS.DOM.getVal('#ProductCommon_OptionListProduct');
        var sexual = ISS.DOM.getVal('#ProductCommon_sexual');
        if(sexual == 'NAM'){
        ISS.BACKEND.request({
            url: ISS.SESSION.getSession('contextPath') + '/service/admin/getProductWidthCategoryM/' + maDMSP,
            type: 'GET',
            success: function (data) {
                var responseInfo = data.responseObject;
                mapAllProductToView(responseInfo);
            }
        });
        }
        else {
            ISS.BACKEND.request({
                url: ISS.SESSION.getSession('contextPath') + '/service/admin/getProductWidthCategoryF/' + maDMSP,
                type: 'GET',
                success: function (data) {
                    var responseInfo = data.responseObject;
                    mapAllProductToView(responseInfo);
                }
            });
        }
    });

    ISS.EVENT.bindEvent('#ProductCommon_Delete', 'click', function () {
        var _maSP = [];
        ISS.DOM.forEach('#form-ProductCommon input[type="checkbox"]:checked', function(){
            _maSP.push($(this).val());
        });

        if(_maSP.length == 1) {
//            var _url = '/service/admin/toProductDetailPage/' + _maSP[0];
            ISS.BACKEND.request({
//            url: SERVER.contextPath + '/service/admin/getDataDetailOfDataCommon/' + maSP,
                url: ISS.SESSION.getSession('contextPath') + '/service/admin/getDataDetailOfDataCommon/' + _maSP[0],
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    var responseContent = data.responseObject;
                    if(responseContent.chiTietSanPhams[0] != null){
//                        alert('Co chi tiet');
                        ISS.DOM.removeClass('#boxTrackDeleteConfirmContinue', 'hideBox');
                    } else {
//                        alert('Ko co chi tiet');
                        var _sanPham = {};
                        _sanPham.maSP = _maSP[0];
                        ISS.BACKEND.request({
                            url: ISS.SESSION.getSession('contextPath') + '/service/admin/deleteProductCommon/',
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json'
                            },
                            type: 'POST',
                            dataType: 'json',
                            data: JSON.stringify(_sanPham),
                            success: function (data) {
                                if(data.code == 0) {
//                                    toDetailPage();
//                        ISS.DOM.removeClass('#boxTrackDeleteSuccess', 'hideBox');
//                        ISS.CONTROL.unLockScreen();
                                }
                            }
                        });
                    }
//                    mapAllProductDetailSearchToView(responseContent);
//                    mapDataProductComplete(responseContent);
//                ISS.CONTROL.unLockScreen();
                }
            });
        }
        else {
            alert('Không được chọn hơn một dòng');
        }
    });

    ISS.EVENT.bindEvent('#buttonDeleteProductCommonContinue_Agree', 'click', function () {
        ISS.DOM.addClass('#boxTrackSuccessAddProductConfirm', 'hideBox');
        toDetailPage();
    });

    ISS.EVENT.bindEvent('#buttonDeleteProductCommonContinue_Cancel', 'click', function () {
        ISS.DOM.addClass('#boxTrackSuccessAddProductConfirm', 'hideBox');
        /*var _url = '/service/admin/toProductCommonPage';
        ISS.WINDOW.location(_url);*/
    });

}

function toDetailPage() {
    var _maSP = [];
    ISS.DOM.forEach('#form-ProductCommon input[type="checkbox"]:checked', function(){
        _maSP.push($(this).val());
    });

    if(_maSP.length == 1) {
        var _url = '/service/admin/toProductDetailPage/' + _maSP[0];
        ISS.WINDOW.location(_url);
    }
    else {
        alert('Không được chọn hơn một dòng');
    }
}

function toEditPage() {
    var _maSP = [];
    ISS.DOM.forEach('#form-ProductCommon input[type="checkbox"]:checked', function(){
        _maSP.push($(this).val());
    });

    if(_maSP.length == 1) {
        var _url = '/service/admin/toProductCommonPage/' + _maSP[0];
        ISS.WINDOW.location(_url);
    }
    else {
        alert('Không được chọn hơn một dòng');
    }
}

function sendInfo() {
    var product = {};
    var category = {};

    product.maSP = ISS.DOM.getVal('#ProductCommon_code');
    product.tenSP = ISS.DOM.getVal('#ProductCommon_name');
    product.thongTin = ISS.DOM.getVal('#ProductCommon_information');
    product.doiTuong = ISS.DOM.getVal('#ProductCommon_sexual');
    category.maLoaiDMSP = ISS.DOM.getVal('#ProductCommon_listProduct');
    product.loaiDanhMucSanPham = category;

    ISS.BACKEND.request({
        url: '../../service/admin/header/adProductCommon_add',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(product),
        success: function (data) {
            var code = data.code;
            loadDataComplete(code);
            ISS.DOM.removeClass('#boxTrackSuccessAddProductConfirm', 'hideBox');
        }
    });
}

function sendDetailInfo() {

    var productDetail = {};
    var product = {}, size = {}, color = {}, motif ={};

    productDetail.maCTSP = ISS.DOM.getVal('#ProductDetail_code');
    productDetail.giaSP = ISS.DOM.getVal('#ProductDetail_unitPrice');
    productDetail.soLuong = ISS.DOM.getVal('#ProductDetail_quantity');

    product.maSP = ISS.DOM.getVal('#ProductCommon_code');
    productDetail.sanPham = product;

    size.maSize = ISS.DOM.getVal('#ProductDetail_size');
    productDetail.kichThuoc = size;

    color.maMau = ISS.DOM.getVal('#ProductDetail_color');
    productDetail.mauSac = color;

    motif.maHoaTiet = ISS.DOM.getVal('#ProductDetail_motif');
    productDetail.hoaTiet = motif;

    ISS.BACKEND.request({
        url: '../../service/admin/ad_AddProductDetail',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(productDetail),
        success: function (data) {
            var code = data.code;
            loadDataDetailComplete(code);
        }
    });
}


function mapAllProductCategoryToViewInProduct(productcategory) {
    var html = '<option selected="selected" value="default_value">Mời chọn</option>';
    for(var i=0; i<productcategory.length; i++) {
        html += '<option value="' + productcategory[i].maLoaiDMSP + '">' + productcategory[i].tenLoaiDMSP + '</option>';
    }
    ISS.DOM.html('#ProductCommon_listProduct', html);
    ISS.DOM.html('#ProductCommon_OptionListProduct', html);
}

function loadDataComplete(code){
    if (code == 0){
        ISS.DOM.removeClass('#boxTrackConfirm', 'hideBox');
        ISS.DOM.removeClass('#buttonProductCommon_Quit', 'size1of3');
        ISS.DOM.removeClass('#buttonProductCommon_Add1', 'size1of3');
        ISS.DOM.removeClass('#buttonProductCommon_Detail_Retype', 'size1of3');
        ISS.DOM.removeClass('#buttonProductCommon_Detail', 'hideBox');
        ISS.DOM.addClass('#buttonProductCommon_Quit', 'size1of4');
        ISS.DOM.addClass('#buttonProductCommon_Add1', 'size1of4');
        ISS.DOM.addClass('#buttonProductCommon_Detail_Retype', 'size1of4');
    }
    else{
        alert('Thêm sản phẩm mới thất bại');
    }
}

function loadDataDetailComplete(code){
    if (code == 0){
        ISS.DOM.removeClass('#boxTrackConfirmPicture', 'hideBox');
        ISS.DOM.removeClass('#buttonProductDetail_Retype', 'size1of3');
        ISS.DOM.removeClass('#buttonProductDetail_Add1', 'size1of3');
        ISS.DOM.removeClass('#buttonProductDetail_Cancel1', 'size1of3');
        ISS.DOM.removeClass('#buttonProductDetail_Picture', 'hideBox');
        ISS.DOM.addClass('#buttonProductDetail_Retype', 'size1of4');
        ISS.DOM.addClass('#buttonProductDetail_Add1', 'size1of4');
        ISS.DOM.addClass('#buttonProductDetail_Cancel1', 'size1of4');
    }
    else{
        alert('Thêm chi tiết cho sản phẩm này thất bại');
    }
}

function hideBoxConfirm() {
    ISS.DOM.addClass('#boxTrackConfirm', 'hideBox');
}

function clearValidate() {
    ISS.DOM.removeClass('#AdPost_Code', 'error');
    ISS.DOM.removeClass('#AdPost_Title', 'error');
}

function validate() {
    var result = true;
    return result;
}

function mapAllProductToView(product) {
    var rows = product.length;
    var columns = 1;
    var str = '';

        str += '<table id="ProductTable" class="tableMemberWidth align-center">';
        str += '<thead>';
        str += '   <tr>';
        str += '       <th class="columnProductSTT">STT</th>';
        str += '       <th class="columnProductStick">Tick</th>';
        str += '       <th class="columnProductCode">Mã SP</th>';
        str += '       <th class="columnProductList">Danh mục</th>';
        str += '       <th class="columnProductTitle">Tên sản phẩm</th>';
        str += '       <th class="columnProductInfo">Thông tin</th>';
        str += '       <th class="columnProductSexual">ĐT</th>';
//        str += '       <th class="columnProductButtonDetail"></th>';
        str += '   </tr>';
        str += '</thead>';
        str += '<tbody>';
        for(var i = 0; i < rows; i++){
            if (i%2==0){
                str += '<tr onmouseover="set_hover(this);" onmouseout="remove_hover(this)" id="showData" class="column-Light tableTransparent">';
            }else{
                str += '<tr onmouseover="set_hover(this);" onmouseout="remove_hover(this)" id="showData" class="column-Light tableTransparent">';
            }

            for (j = 0; j < columns; j++){
                str += '<td class="columnProductSTT tableProductPadding">' + (i+1) + '</td>';
                str += '<td class="columnStick tableProductPadding"><input onclick="highlight_row(this)" id="' + product[i].maSP + '" type="checkbox" value="' + product[i].maSP + '"/></td>';
                str += '<td class="columnStick tableProductPadding" id="' + product[i].maSP + '">' + product[i].maSP + '</td>';
                str += '<td class="columnProductList tableProductPadding" id="' + product[i].loaiDanhMucSanPham.maLoaiDMSP + '">' + product[i].loaiDanhMucSanPham.tenLoaiDMSP + '</td>';
                str += '<td class="columnProductTitle tableProductPadding">' + product[i].tenSP + '</td>';
                str += '<td class="columnProductInfo tableProductPadding" title="' + product[i].thongTin + '">' + product[i].thongTin.trunc(140,true) + '</td>';
                str += '<td class="columnProductSexual tableProductPadding">' + product[i].doiTuong + '</td>';
//                str += '<td class="columnProductButtonDetail tableProductPadding"><button id="ProductCommon_Search_' + product[i].maSP + '" class="btn btn-dark login__button" type="button">CHI TIẾT</button></td>';
            }
            str += '</tr>';
        }
        str +=   '</tbody>';
        str += '</table>';

    ISS.DOM.html('#ProductCommon_All', str);

}

function mapAllColorToView(color) {
    var html = '<option selected="selected" value="default_value">Chọn màu sắc</option>';
    for(var i=0; i<color.length; i++) {
        html += '<option value="' + color[i].maMau + '">' + color[i].tenMau + '</option>';
    }
    ISS.DOM.html('#ProductDetail_color', html);
}

function mapAllSizeToView(size) {
    var html = '<option selected="selected" value="default_value">Chọn size</option>';
    for(var i=0; i<size.length; i++) {
        html += '<option value="' + size[i].maSize + '">' + size[i].tenSize + ' - ' + size[i].loaiDanhMuc.tenLoai + '</option>';
    }
    ISS.DOM.html('#ProductDetail_size', html);
}

function mapAllMotifToView(motif) {
    var html = '<option selected="selected" value="default_value">Chọn họa tiết</option>';
    for(var i=0; i<motif.length; i++) {
        html += '<option value="' + motif[i].maHoaTiet + '">' + motif[i].tenHoaTiet + '</option>';
    }
    ISS.DOM.html('#ProductDetail_motif', html);
}
